package com.xlhl.init.common;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xlhl.init.anno.NotSelect;
import com.xlhl.init.anno.QueryType;
import com.xlhl.init.anno.QueryWrapperSort;

import java.io.Serializable;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 实现这个类会自动根据 {@link BaseRequestBody#getSort} 中的排序条件进行排序
 *
 * @param <T> Java 实体类
 * @author xlhl
 */
public interface QueryWrapperService<T extends Serializable> {

    /**
     * 根据 {@link NotSelect} 注解构造查询字段
     *
     * @param wrapper
     * @param entity
     * @return
     */
    default QueryWrapper<T> getQueryWrapperFilterByNotSelect(QueryWrapper<T> wrapper, Class<T> entity) {
        Field[] fields = entity.getDeclaredFields();
        List<String> selectFieldNames = new ArrayList<>(fields.length);
        for (Field field : fields) {

            NotSelect notSelect = field.getAnnotation(NotSelect.class);
            if (notSelect == null) {
                field.setAccessible(true);
                selectFieldNames.add(StrUtil.toUnderlineCase(field.getName()));
            }
        }

        wrapper.select(selectFieldNames);

        return wrapper;
    }

    /**
     * 根据 {@link NotSelect} 注解构造查询字段
     *
     * @param body
     * @param entity
     * @return
     */
    default QueryWrapper<T> getQueryWrapperFilterByNotSelect(BaseRequestBody body, Class<T> entity) {
        return getQueryWrapperFilterByNotSelect(getQueryWrapper(body, entity), entity);
    }


    /**
     * 获取参数中的排序条件
     *
     * @param body
     * @param clazz Entity Class
     * @return
     */
    default QueryWrapper<T> getSortQueryWrapper(BaseRequestBody body, Class<T> clazz) {
        QueryWrapper<T> queryWrapper = new QueryWrapper<>();

        Map<String, String> sort = body.getSort();

        if (CollUtil.isEmpty(sort)) {
            Field[] fields = clazz.getDeclaredFields();
            for (Field field : fields) {
                QueryWrapperSort wrapperSort = field.getAnnotation(QueryWrapperSort.class);
                if (wrapperSort != null) {
                    QueryWrapperSort.SortType sortType = wrapperSort.value();
                    String filedName = getFiledName(field);
                    switch (sortType) {
                        case ASC -> queryWrapper.orderByAsc(filedName);
                        case DESC -> queryWrapper.orderByDesc(filedName);
                        default -> {
                            //  ignore
                        }
                    }
                }
            }
        } else {
            for (String key : sort.keySet()) {
                queryWrapper.orderBy(true, "ascend".equals(sort.get(key)), StrUtil.toUnderlineCase(key));
            }
        }

        return queryWrapper;
    }

    /**
     * 获取查询条件
     * 会自动把参数字段转驼峰命名
     * <p>
     * 没有被 {@link QueryType} 修饰的属性会被忽略
     *
     * @param body  请求体对象
     * @param clazz Entity Class
     * @return 构建好的QueryWrapper
     */
    default QueryWrapper<T> getQueryWrapperByQueryType(BaseRequestBody body, Class<T> clazz) {
        QueryWrapper<T> queryWrapper = getSortQueryWrapper(body, clazz);

        Field[] fields = body.getClass().getDeclaredFields();

        for (Field field : fields) {
            field.setAccessible(true);

            QueryType queryType = field.getAnnotation(QueryType.class);

            if (queryType == null) {
                continue;
            }

            QueryType.Type type = queryType.value();
            try {
                Object value = field.get(body);
                if (ObjUtil.isNotNull(value) || ObjUtil.isNotEmpty(value)) {
                    processField(queryWrapper, field, value, type);
                }
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }

        return queryWrapper;
    }

    /**
     * 字段处理
     *
     * @param queryWrapper
     * @param field
     * @param value
     * @param type
     */
    default void processField(QueryWrapper<T> queryWrapper, Field field, Object value, QueryType.Type type) {
        String fieldName = getFiledName(field);
        switch (type) {
            //  模糊查询
            case LIKE -> queryWrapper.like(fieldName, value);
            //  精确匹配
            case EQ -> queryWrapper.eq(fieldName, value);
            //  区间查询
            case BETWEEN -> processBetween(queryWrapper, fieldName, (List<?>) value);
            //  大于
            case GREATER_THAN -> queryWrapper.gt(fieldName, value);
            //  小于
            case LESS_THAN -> queryWrapper.lt(fieldName, value);
            default -> {/*不做处理*/}
        }
    }

    /**
     * 处理 Between 类型
     *
     * @param queryWrapper
     * @param fieldName
     * @param values
     */
    default void processBetween(QueryWrapper<T> queryWrapper, String fieldName, List<?> values) {
        if (CollUtil.isNotEmpty(values)) {
            Object left = values.get(0);
            queryWrapper.ge(ObjUtil.isNotNull(left), fieldName, left);

            if (values.size() > 1) {
                Object right = values.get(1);
                queryWrapper.le(ObjUtil.isNotNull(right), fieldName, right);
            }
        }
    }

    /**
     * 获取字段名称，默认使用驼峰转下划线命名
     *
     * @param field
     * @return
     */
    default String getFiledName(Field field) {
        return StrUtil.toUnderlineCase(field.getName());
    }

    /**
     * 构造 Mybatis-Plus 条件
     *
     * @param body
     * @param clazz
     * @return
     */
    default QueryWrapper<T> getQueryWrapper(BaseRequestBody body, Class<T> clazz) {
        return getQueryWrapperByQueryType(body, clazz);
    }
}
